package org.jeecg.modules.collection.webController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mongodb.DuplicateKeyException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.collection.entity.CollectionProductDTO;
import org.jeecg.modules.collection.entity.JkCollection;
import org.jeecg.modules.collection.service.IJkCollectionService;
import org.jeecg.modules.papers.entity.JkPapers;
import org.jeecg.modules.papers.service.IJkPapersService;
import org.jeecg.modules.paten.entity.JkPatentInfo;
import org.jeecg.modules.paten.service.IJkPatentInfoService;
import org.jeecg.modules.product.entity.JkProduct;
import org.jeecg.modules.product.service.IJkProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.jeecg.common.api.vo.Result;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name="jk_collection")
@RestController
@RequestMapping("/api/jkCollection")
@Slf4j
public class JKWebCollectionController {

    @Autowired
    private IJkCollectionService jkCollectionService;

    @Autowired
    private IJkProductService jkProductService;

    @Autowired
    private IJkPatentInfoService jkPatentInfoService;

    @Autowired
    private IJkPapersService jkPapersService;

    /**
     * 分页列表查询
     *
     * @param jkCollection
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "jk_collection-分页列表查询")
    @Operation(summary="jk_collection-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<JkCollection>> queryPageList(JkCollection jkCollection,
                                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<JkCollection> queryWrapper = QueryGenerator.initQueryWrapper(jkCollection, req.getParameterMap());
        Page<JkCollection> page = new Page<JkCollection>(pageNo, pageSize);
        IPage<JkCollection> pageList = jkCollectionService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     *   添加
     *
     * @param jkCollection
     * @return
     */
    @AutoLog(value = "jk_collection-添加")
    @Operation(summary="jk_collection-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody JkCollection jkCollection) {
        try {
            jkCollectionService.save(jkCollection);

        } catch (DuplicateKeyException e) {
            log.error("重复收藏记录：{}", e.getMessage());
            return Result.OK("该收藏已存在");
        }
        return Result.OK("添加成功！");
    }


    @GetMapping("/myCollections")
    public Result<Map<String,IPage<?>>> pageUserCollectedProducts(
            @RequestBody JkCollection jkCollection,
            @RequestParam(required = false, defaultValue = "1") long pageNo,
            @RequestParam(required = false, defaultValue = "10") long pageSize,
            HttpServletRequest req
    ) {
       // int type = jkCollection.getType();
        Map<String,IPage<?>> map = new HashMap<>();

               // 1. 查询用户收藏的商品ID
               QueryWrapper<JkCollection> collectionQuery = new QueryWrapper<>();
               collectionQuery.eq("user_id", jkCollection.getUserId())
                       .eq("type", 1); // 类型为1表示商品

               List<JkCollection> collections = jkCollectionService.list(collectionQuery);
               List<Integer> productIds = collections.stream()
                       .map(JkCollection::getCollectId)
                       .collect(Collectors.toList());

               if (!productIds.isEmpty()) {
                   JkProduct jkProduct = new JkProduct();
                   QueryWrapper<JkProduct> productWrapper = QueryGenerator.initQueryWrapper(jkProduct, req.getParameterMap());
                   productWrapper.in("id", productIds); // 添加IN条件
                   Page<JkProduct> page = new Page<JkProduct>(pageNo, pageSize);
                   IPage<JkProduct> pageList = jkProductService.page(page, productWrapper);
                   map.put("product",pageList);
               }

        // 2. 查询用户收藏的专利ID
        QueryWrapper<JkCollection> patenCollectionQuery = new QueryWrapper<>();
        patenCollectionQuery.eq("user_id", jkCollection.getUserId())
                .eq("type", 2); // 类型为1表示商品

        List<JkCollection> patenCollections = jkCollectionService.list(patenCollectionQuery);
        List<Integer> patenIds = patenCollections.stream()
                .map(JkCollection::getCollectId)
                .collect(Collectors.toList());

        if (!patenIds.isEmpty()) {
            JkPatentInfo jkPatentInfo = new JkPatentInfo();
            QueryWrapper<JkPatentInfo> patenWrapper = QueryGenerator.initQueryWrapper(jkPatentInfo, req.getParameterMap());
            patenWrapper.in("id", patenIds); // 添加IN条件
            Page<JkPatentInfo> patenPage = new Page<JkPatentInfo>(pageNo, pageSize);
            IPage<JkPatentInfo> patenPageList = jkPatentInfoService.page(patenPage, patenWrapper);
            map.put("paten",patenPageList);
        }


        // 3. 查询用户收藏的论文ID
        QueryWrapper<JkCollection> papersCollectionQuery = new QueryWrapper<>();
        papersCollectionQuery.eq("user_id", jkCollection.getUserId())
                .eq("type", 3);

        List<JkCollection> papersCollections = jkCollectionService.list(papersCollectionQuery);
        List<Integer> papersIds = papersCollections.stream()
                .map(JkCollection::getCollectId)
                .collect(Collectors.toList());

        if (!papersIds.isEmpty()) {
            JkPapers jkPapers = new JkPapers();
            QueryWrapper<JkPapers> papersWrapper = QueryGenerator.initQueryWrapper(jkPapers, req.getParameterMap());
            papersWrapper.in("id", papersIds); // 添加IN条件
            Page<JkPapers> page = new Page<JkPapers>(pageNo, pageSize);
            IPage<JkPapers> papersPageList = jkPapersService.page(page, papersWrapper);
            map.put("papers",papersPageList);
        }






        return Result.OK(map);
    }


    @AutoLog(value = "jk_collection-通过id删除")
    @Operation(summary="jk_collection-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        jkCollectionService.removeById(id);
        return org.jeecg.common.api.vo.Result.OK("删除成功!");
    }

}
